package ysq.xyg.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageInfo;
import com.github.pagehelper.StringUtil;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import ysq.xyg.model.Activity;
import ysq.xyg.model.Item;
import ysq.xyg.model.info.ActivityInfo;
import ysq.xyg.model.info.Page;
import ysq.xyg.model.info.ReturnInfo;
import ysq.xyg.service.ActivityService;
import ysq.xyg.service.ItemService;
import ysq.xyg.service.MemberService;
import ysq.xyg.service.WinNumService;
import ysq.xyg.util.BaseConstant;
import ysq.xyg.util.BaseUtil;
import ysq.xyg.util.DateUtil;

import javax.annotation.Resource;
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.util.Date;

/**
 * 商品活动
 *
 * @author congcong tao
 * @create 2018/8/8 下午9:40
 */
@Controller
@RequestMapping("/activity")
public class ActivityController extends BaseController {

    private static Logger log= LoggerFactory.getLogger(ActivityController.class);
    @Resource
    private ActivityService activityService;
    @Resource
    private ItemService itemService;
    @Resource
    private WinNumService winNumService;
    @Resource
    private MemberService memberService;

    private Activity activity;

    @RequestMapping("/listPage")
    public ModelAndView list(String status){
        ModelAndView view = new ModelAndView("/activityList");
        view.addObject("status", status);
        return view;
    }

    @RequestMapping(value = "/jsonList",method = RequestMethod.POST)
    public @ResponseBody JSONObject jsonList(Activity activity, Page page) throws MalformedURLException, UnsupportedEncodingException {
        PageInfo<Activity> pageInfo = activityService.pageInfo(activity, page.getLimit(), page.getPage());
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("code", 0);
        jsonObject.put("msg", "");
        jsonObject.put("count", pageInfo.getTotal());
        if (pageInfo != null && pageInfo.getList() != null && pageInfo.getList().size() > 0) {
            JSONObject row = null;
            JSONArray rows = new JSONArray();
            for (Activity item : pageInfo.getList()) {
                row=new JSONObject();
                row.put("id", item.getId());
                row.put("title", item.getTitle());
                row.put("totalNum", item.getTotalNum());
                row.put("readyNum", item.getReadyNum());
                row.put("itemTitle", item.getItemTitle());
                row.put("progress", item.getProgress() + "%");
                row.put("createTime", DateUtil.DateToStr(item.getCreateTime(), DateUtil.DATE_TIME_PATTERN));
                rows.add(row);
            }
            jsonObject.put("data",rows);
        }
        return jsonObject;
    }

    @RequestMapping(value = "/jsonListOrder",method = RequestMethod.POST)
    public @ResponseBody JSONObject jsonListOrder(Activity activity, Page page) throws MalformedURLException, UnsupportedEncodingException {
        PageInfo<Activity> pageInfo = activityService.pageInfoOrder(activity, page.getLimit(), page.getPage());
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("code", 0);
        jsonObject.put("msg", "");
        jsonObject.put("isLastPage", pageInfo.isIsLastPage());
        jsonObject.put("count", pageInfo.getTotal());
        if (pageInfo != null && pageInfo.getList() != null && pageInfo.getList().size() > 0) {
            JSONObject row = null;
            JSONArray rows = new JSONArray();
            for (Activity item : pageInfo.getList()) {
                row=new JSONObject();
                row.put("id", item.getId());
                row.put("itemId", item.getItemId());
                row.put("title", item.getTitle());
                row.put("itemTitle", item.getItemTitle());
                row.put("imageOne", item.getImageOne());
                row.put("progress", item.getProgress());
                row.put("createTime", DateUtil.DateToStr(item.getCreateTime(), DateUtil.DATE_TIME_PATTERN));
                rows.add(row);
            }
            jsonObject.put("data",rows);
        }
        return jsonObject;
    }

    @RequestMapping(value = "/jsonPastActList",method = RequestMethod.POST)
    public @ResponseBody
    JSONObject jsonPastActList(Activity activity, Page page) throws MalformedURLException, UnsupportedEncodingException {
        PageInfo<Activity> pageInfo = activityService.pagePastActInfo(activity, page.getLimit(), page.getPage());
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("code", 0);
        jsonObject.put("msg", "");
        jsonObject.put("isLastPage", pageInfo.isIsLastPage());
        jsonObject.put("count", pageInfo.getTotal());
        if (pageInfo != null && pageInfo.getList() != null && pageInfo.getList().size() > 0) {
            JSONObject row = null;
            JSONArray rows = new JSONArray();
            for (Activity item : pageInfo.getList()) {
                row=new JSONObject();
                row.put("id", item.getId());
                row.put("itemTitle", item.getItemTitle());
                row.put("periodsNum", item.getPeriodsNum());
                row.put("imageOne", item.getImageOne());
                // 使用昵称
                if (StringUtil.isNotEmpty(item.getMemberName())) {
                    row.put("memberName", BaseUtil.decodeBase64(item.getMemberName()));
                }
                row.put("winInNum", item.getWinInNum());
                row.put("winningNum", item.getWinningNum());
                row.put("totalNum", item.getTotalNum());
                row.put("updateTime", DateUtil.DateToStr(item.getUpdateTime(), DateUtil.DATE_TIME_PATTERN));
                rows.add(row);
            }
            jsonObject.put("data",rows);
        }
        return jsonObject;
    }

    @RequestMapping(value = "/selectEntity",method = RequestMethod.GET)
    public ModelAndView selectEntity(String id, String itemId){
        ModelAndView view = new ModelAndView("/activityUpdateOrSave");
        activity = activityService.selectByPrimaryKey(id);
        int periodsNum;
        if (StringUtils.isNotEmpty(itemId)) {
            periodsNum = activityService.selectMaxPeriods(itemId);
            periodsNum++;
        } else {
            itemId = activity.getItemId();
            periodsNum = activity.getPeriodsNum();
        }
        Item item = itemService.selectByPrimaryKey(itemId);
        // 查询相关物品的期数
        view.addObject("oldPeriodsNum", periodsNum);
        view.addObject("item", item);
        view.addObject("activity", activity);
        return view;
    }

    @RequestMapping(value = "/updateOrAddEntity",method = RequestMethod.POST)
    public @ResponseBody JSONObject updateOrAddEntity(ActivityInfo activityInfo) {
        ReturnInfo returnInfo = new ReturnInfo();
        JSONObject jsonObject = new JSONObject();
        if (StringUtil.isEmpty(activityInfo.getId())) {
            activity = new Activity();
            String id = BaseUtil.uId();
            activity.setId(id);
            activity.setItemId(activityInfo.getItemId());
            activity.setPeriodsNum(activityInfo.getPeriodsNum());
            activity.setTotalNum(activityInfo.getTotalNum());
            activity.setIsAuto(activityInfo.getIsAuto());
            activity.setStatus(BaseConstant.ACTIVITY_ING);
            activity.setTitle(activityInfo.getTitle());
            activity.setCreateTime(new Date());
            int flag = activityService.insert(activity);
            if(flag <= 0){
                returnInfo = new ReturnInfo(BaseConstant.FAIL, BaseConstant.DATABASE_ERROR_INSERT);
            }
            // 发布活动的时候生成中奖num号
            int i = winNumService.generateWinNum(activityInfo.getTotalNum(), id);
            if (i <= 0) {
                returnInfo = new ReturnInfo(BaseConstant.FAIL, BaseConstant.DATABASE_ERROR_INSERT);
            }
        } else {
            activity = activityService.selectByPrimaryKey(activityInfo.getId());
            activity.setItemId(activityInfo.getItemId());
            activity.setPeriodsNum(activityInfo.getPeriodsNum());
            activity.setTotalNum(activityInfo.getTotalNum());
            activity.setIsAuto(activityInfo.getIsAuto());
            activity.setTitle(activityInfo.getTitle());
            int id = activityService.updateByPrimaryKey(activity);
            if (id <= 0) {
                returnInfo = new ReturnInfo(BaseConstant.FAIL, BaseConstant.DATABASE_ERROR_UPDATE);
            }
        }
        jsonObject.put("returnInfo", returnInfo);
        return jsonObject;
    }

    @RequestMapping(value = "/deleteEntity",method = RequestMethod.GET)
    public @ResponseBody JSONObject deleteEntity(String id){
        ReturnInfo returnInfo=new ReturnInfo();
        JSONObject jsonObject=new JSONObject();
        if(StringUtil.isEmpty(id)){
            returnInfo=new ReturnInfo(BaseConstant.FAIL, BaseConstant.DATABASE_ERROR_CANSHU);
        }else{
            int ids = activityService.deleteByPrimaryKey(id);
            if(ids <= 0){
                returnInfo = new ReturnInfo(BaseConstant.FAIL, BaseConstant.DATABASE_ERROR_DELETE);
            }
        }
        jsonObject.put("returnInfo",returnInfo);
        return jsonObject;
    }

    @RequestMapping(value = "/winningNum",method = RequestMethod.GET)
    public @ResponseBody JSONObject winningNum(String memberId, String activityId, String itemId,int num){
        ReturnInfo returnInfo = new ReturnInfo();
        JSONObject jsonObject = new JSONObject();
        try {
            // 查询没有memberId的
            long count = winNumService.selectCountNoMember(activityId);
            if (count == 0) {
                // long winCount = winNumService.selectCountWin(activityId);
                returnInfo = new ReturnInfo(BaseConstant.FAIL_CODE_THREE, "该次已结束,请下期购买");
            } else {
                int flag = winNumService.winningNum(memberId, activityId, num,itemId);
                if (flag == -1) {
                    returnInfo = new ReturnInfo(BaseConstant.FAIL, "您的钻石不足,请充值");
                }
                if (flag == -2) {
                    returnInfo = new ReturnInfo(BaseConstant.FAIL, "您购买过多,请包围");
                }
                if (flag == 0) {
                    returnInfo = new ReturnInfo(BaseConstant.FAIL, "该商品已被抢购完");
                }
            }
        } catch (RuntimeException e) {
            returnInfo = new ReturnInfo(BaseConstant.FAIL_CODE_FOUR, "该商品已被抢购完");
        }
        jsonObject.put("returnInfo",returnInfo);
        return jsonObject;
    }
}
